package com.sl.au.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Attachment;
import com.sl.au.entity.Contract;
import com.sl.au.entity.Customer;
import com.sl.au.entity.DeviceDetail;
import com.sl.au.entity.MaintainScheme;
import com.sl.au.entity.QuoteDevice;
import com.sl.au.entity.SaleArea;
import com.sl.au.service.AfterSaleMaintainService;
import com.sl.au.service.ContractService;
import com.sl.au.service.CustomerService;
import com.sl.au.service.OptionService;
import com.sl.au.service.SaleAreaService;
import com.sl.au.service.UserService;

/*
 * 售后设备信息
 */

@RestController
@RequestMapping(value = "/ui/afterSaleDeviceInfo")
public class AfterSaleDeviceInfoController extends BaseController {

	@Autowired
	CustomerService customerService;
	
	@Autowired
	SaleAreaService saleAreaService;
	
	@Autowired
	OptionService  optionService;
	
	@Autowired
	ContractService  contractService;
	
	@Autowired
	AfterSaleMaintainService  afterSaleMaintainService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("afterSaleDeviceInfo/deviceInfoindex");
		return modelAndView;
	}
	
	@RequestMapping(value="getpage",method = RequestMethod.GET)
	public Map<String, Object> getServicePage(HttpServletRequest request){
		Map<String, Object> map=new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		long count = 0;
		if (key != null) {
			List<Contract> contracts=contractService.getAfterSaleContracts(start, length, key, null, null);
			count = contractService.getRepository().getAfterSaleContractsCount2(key);
			map.put("data", contracts);
		} else {
			List<Contract> contracts=contractService.getAfterSalePage(start, length, key, null, null);
			count = contractService.getRepository().getAfterSaleContractsCount1();
			map.put("data", contracts);
		}
		
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 打开新增页面
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public ModelAndView add(HttpServletRequest request) {
		ModelAndView mv = createLayoutView("afterSaleDeviceInfo/deviceInfoAdd");
		List<Object> supplierCodes = new ArrayList<Object>();
		List<Object> codes = contractService.getRepository().getContractSupplierCodeList1();
		supplierCodes.add("");
		for( Object code : codes){
			supplierCodes.add(code);
		}
		mv.addObject("supplierCodes", supplierCodes);
		return mv;
	}
	
	/**
	 * 获取审批已通过且未被添加的合同
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getContract",method = RequestMethod.GET)
	public Map<String, Object> getContract(HttpServletRequest request){
		Map<String, Object> map=new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		long count = 0;
		if (key == null) {
			key = "";
		}
		List<Contract> contracts=afterSaleMaintainService.getPassContracts(start, length, key, null, null);
		count = afterSaleMaintainService.getRepository1().getPassContractsCount(key);
		map.put("data", contracts);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 打开编辑页面
	 * @return
	 */
	@RequestMapping(value = "/editDevice/{id}", method = RequestMethod.GET)
	public ModelAndView editDevice(@PathVariable String id, HttpServletRequest request) {
		ModelAndView mv = createLayoutView("afterSaleDeviceInfo/deviceInfoEdit");
		Contract contract = contractService.getRepository().findOne(id);
		mv.addObject("contract", contract);
		return mv;
	}
	
	/**
	 * 项目合同细目泵数据显示
	 * @return
	 */
	@RequestMapping(value = "getDevice", method = RequestMethod.GET)
	public Map<String, Object> getDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String contractId=request.getParameter("contractID");
		if (contractId==null){
			contractId="";
		}
		List<DeviceDetail> devices = afterSaleMaintainService.getAllDetails(start, length, contractId, null, null);
		Long count = (long) afterSaleMaintainService.getAllDetailsCount(contractId);
		map.put("data", devices);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 保存售后合同
	 * @return
	 */
	@RequestMapping(value = "/saveContract/{id}", method = RequestMethod.GET)
	public Map<String, Object> saveContract(@PathVariable String id,HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Contract contract = contractService.getRepository().findOne(id);
		if (contract != null && (contract.getIsAfterSale()==null || !contract.getIsAfterSale())){
			contract.setIsAfterSale(true);
			contractService.getRepository().save(contract);
		}
		map.put("code", "0");
		return map;
	}
	
	/**
	 * 批量删除售后合同
	 * @return
	 */
	@RequestMapping(value = "/delContract", method = RequestMethod.GET)
	public Map<String, Object> delContract(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids=request.getParameter("ids");
		String[] contractIds = ids.split(",");
		List<Contract> contracts = new ArrayList<Contract>();
		for (String id : contractIds){
			Contract contract = contractService.getRepository().findOne(id);
			if (contract != null && contract.getIsAfterSale()!=null && contract.getIsAfterSale()){
				contract.setIsAfterSale(false);
				contracts.add(contract);
			}
		}
		contractService.getRepository().save(contracts);
		map.put("code", "0");
		return map;
	}
	
	/**
	 * 引入合同初始化设备
	 * @return
	 */
	@RequestMapping(value = "/initialDevice/{contractId}", method = RequestMethod.GET)
	public Map<String, Object> initialDevice(@PathVariable String contractId, 
			  							   HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (contractId!=null){
			afterSaleMaintainService.initialDevice(contractId);
		}
		map.put("code", "0");
		return map;
	}
	
	/**
	 * 保存设备信息
	 * @return
	 */
	@RequestMapping(value = "/saveDevice", method = RequestMethod.POST)
	public Map<String, Object> saveDevice(@RequestBody DeviceDetail deviceDetail, 
			  							   HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (deviceDetail!=null){
			String contractID = null;
			DeviceDetail oldDeviceDetail = null;
			if (deviceDetail.getContractID()!=null && !deviceDetail.getContractID().equals("")){
				contractID = deviceDetail.getContractID();
				Contract contract = contractService.getRepository().findOne(contractID);
				if (contract != null && (contract.getIsAfterSale()==null || !contract.getIsAfterSale())){
					contract.setIsAfterSale(true);
					contractService.getRepository().save(contract);
				}
			}
			if (deviceDetail.getId()!=null && !deviceDetail.getId().equals("")){
				oldDeviceDetail = afterSaleMaintainService.getDeviceDetailRepository().findOne(deviceDetail.getId());
				oldDeviceDetail.setLeaveFactoryCode(deviceDetail.getLeaveFactoryCode());
				oldDeviceDetail.setLeaveFactoryDate(deviceDetail.getLeaveFactoryDate());
				afterSaleMaintainService.getDeviceDetailRepository().save(oldDeviceDetail);
			}
		}
		map.put("code", "0");
		return map;
	}
	
	/**
	 * 数据提交前验证设备出厂编号是否唯一
	 */
	@RequestMapping(value = "/validLeaveFactoryCode/{deviceID}/{leaveFactoryCode}", method = RequestMethod.GET)
	public Map<String, Object> validLeaveFactoryCode(@PathVariable String deviceID, 
												    @PathVariable String leaveFactoryCode, 
												    HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String state = "0";
		if (!StringUtils.hasText(deviceID)){
			deviceID = "0";
		}
		//得到设备出厂编号为leaveFactoryCode的方案
		List<DeviceDetail> dds = new ArrayList<DeviceDetail>();
		if (StringUtils.hasText(leaveFactoryCode)){
			dds = afterSaleMaintainService.getRepository().getDeviceByCode(leaveFactoryCode);
		}
		if (dds.size()>1){
			state = "1";
		}else if (dds.size()==1){
			if (!dds.get(0).getId().equals(deviceID)){
				state = "1";
			}
		}
		map.put("state", state);
		return map;
	}
	/*@RequestMapping(value = "/saveDevice", method = RequestMethod.GET)
	public Map<String, Object> saveDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String infos=request.getParameter("infos");
		String[] params = infos.split(":");
		String code = "1";
		if (StringUtils.hasText(params[0]) && StringUtils.hasText(params[2])){
			Contract contract = contractService.getRepository().findOne(params[0]);
			if (contract != null && (contract.getIsAfterSale()==null || !contract.getIsAfterSale())){
				contract.setIsAfterSale(true);
				contractService.getRepository().save(contract);
			}
			String[] deviceIds = params[1].split(",");
			String str = params[2];
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			Date t = null;
			try {
				t = formatter.parse(str);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			List<QuoteDevice> quoteDevices = new ArrayList<QuoteDevice>();
			for (String id : deviceIds){
				QuoteDevice quoteDevice = contractService.getRepository5().findOne(id);
				quoteDevice.setLeaveFactoryDate(t);
				quoteDevices.add(quoteDevice);
			}
			contractService.getRepository5().save(quoteDevices);
			code = "0";
		}
		
		map.put("code", code);
		return map;
	}*/
	
}
